package com.jiuzhe.commercial.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.Projection;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseFragment;
import com.jiuzhe.commercial.bean.HouseListBean;
import com.jiuzhe.commercial.bean.MapBean;
import com.jiuzhe.commercial.bean.RoomDetailsBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.ui.house.AddHomeStayActivity;
import com.jiuzhe.commercial.ui.house.CityListSelectActivity;
import com.jiuzhe.commercial.ui.house.editor.HomeStayListActivity;
import com.jiuzhe.commercial.utils.RxBus;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jiuzhe.commercial.view.BannerLayout;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by 12078 on 2018/4/19.
 */

public class HouseFragment2 extends BaseFragment implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, GeocodeSearch.OnGeocodeSearchListener {
    @BindView(R.id.head_title)
    TextView headTitle;
    AMapLocationClient mLocationClient;
    OnLocationChangedListener mListener;
    // 声明mLocationOption对象
    AMapLocationClientOption mLocationOption;
    boolean isFirstLoc = true;
    @BindView(R.id.ib_location)
    ImageView ibLocation;
    @BindView(R.id.ib_add)
    ImageView ibAdd;
    @BindView(R.id.ib_switcher)
    ImageView ibSwitcher;
    @BindView(R.id.tv_location)
    TextView tvLocation;

    @BindView(R.id.map)
    TextureMapView mMap;
    private AMap mAmap;
    private MarkerOptions markerOption;
    private String token;
    private String id;
    private GeocodeSearch geocoderSearch; //地理编码
    private String city;
    private float zoom = 12;//地图缩放级别
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private Marker marker;
    private Subscription mSubscription;
    private String mCityLocation;


    @Override
    protected int getLayoutResource() {
        return R.layout.house_fragment;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mMap.onCreate(savedInstanceState);
        Location();
        if (mAmap == null) {
            mAmap = mMap.getMap();
            mAmap.setOnMarkerClickListener(this);
            // setUpMap();
        }
        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(HouseFragment2.this);
        UiSettings settings = mAmap.getUiSettings();
        settings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        setTitle();
        initData();

    }

    private void initData() {
        mSubscription = RxBus.getInstance().toObserverable(HouseListBean.class)
                .subscribe(new Action1<HouseListBean>() {
                    @Override
                    public void call(HouseListBean bean) {
                        mAmap.clear();
                        if (null != city){
                            addMarkersToMap(city);
                        }else {
                            addMarkersToMap(mCityLocation);
                        }
                    }
                });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void Location() {
        try {
            locationClient = new AMapLocationClient(getActivity());
            locationOption = new AMapLocationClientOption();
            // 设置定位模式为低功耗模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            // 设置定位监听
            locationClient.setLocationListener(this);
            locationOption.setOnceLocation(true);//设置为单次定位
            locationClient.setLocationOption(locationOption);// 设置定位参数

            // 启动定位
            locationClient.startLocation();
        } catch (Exception e) {
           // Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_LONG).show();
            locationClient.startLocation();
        }
    }

    private void setTitle() {
        headTitle.setText("房源");
    }


    @OnClick({R.id.ll_location, R.id.ll_add, R.id.ll_switcher})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.ll_location:
                Intent intent = new Intent(getActivity(), CityListSelectActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.ll_add:
                UIUtils.startActivity(AddHomeStayActivity.class);

                break;
            case R.id.ll_switcher:
                UIUtils.startActivity(HomeStayListActivity.class);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    city = data.getStringExtra("city");
                    String lat = data.getStringExtra("lat");
                    String lng = data.getStringExtra("lng");

                    tvLocation.setText(city);
                    geocodeSearch(city);

                    // moveCenter(new LatLng(Double.valueOf(lat)*0.000001,Double.valueOf(lng)*0.000001));
                    // addMarkersToMap(Double.valueOf(lat)*0.000001,Double.valueOf(lng)*0.000001);
                }
                break;
            default:
                break;
        }
    }

    private void geocodeSearch(String city) {
        //构造 GeocodeSearch 对象，并设置监听。
        //地理编码事件监听
//通过GeocodeQuery设置查询参数,调用getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法发起请求。
//address表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode都ok
        GeocodeQuery query = new GeocodeQuery(city, city);
        geocoderSearch.getFromLocationNameAsyn(query);
    }


    /**
     * 地图移动 到定位点
     *
     * @param latLng
     */
    private void moveCenter(LatLng latLng) {
        if (null != mAmap) {
            mAmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //检测系统是否打开开启了地理定位权限
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMap.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFirstLoc = true;
//        mLocationClient.stopLocation();
        ///销毁定位客户端。
        //销毁定位客户端之后，若要重新开启定位请重新New一个AMapLocationClient对象。
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //   mAmap = null;
        if (mMap != null) {
            mMap.onDestroy();
        }


        if (locationClient != null) {
            locationClient.stopLocation();//停止定位
            locationClient.onDestroy();
        }

        if (mSubscription != null ) {
            if(!mSubscription.isUnsubscribed()){
                mSubscription.unsubscribe();
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();//获取经度
                mCityLocation = aMapLocation.getCity();
                // 城市信息 aMapLocation.getCity();//城市信息

                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    tvLocation.setText(aMapLocation.getCity());
                    //设置缩放级别
                    //  mAmap.moveCamera(CameraUpdateFactory.zoomTo(12));
                    //将地图移动到定位点
                    mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    //  mListener.onLocationChanged(aMapLocation);
                    isFirstLoc = false;
                    mAmap.clear();
                    addMarkersToMap(mCityLocation);
                }
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                //   Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_LONG).show();
                locationClient.startLocation();
            }
        }
    }

    /**
     * 地图上添加 图标
     *
     * @param
     * @param
     */
    private void addMarkersToMap(String city) {
        HashMap<String, String> map = new HashMap<>();
        map.put("merchantId", SPUtil.getString(getActivity(), Constants.MERCHANTID));
        map.put("cityName", city);
        token = SPUtil.getString(getActivity(), Constants.TOKEN);
        id = SPUtil.getString(getActivity(), Constants.ID);
        String autoSignStr = Constants.MAP_MARKERS.substring(Constants.MAP_MARKERS.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        HttpClient.post(this, Constants.MAP_MARKERS, map, new CallBack<List<MapBean>>() {

            int sumLats = 0;
            int sumLngs = 0;
            int total = 0;

            @Override
            public void onSuccess(List<MapBean> result) {
                if (result.size() > 0) {
                    for (MapBean dataBean : result) {
                        markerOption = new MarkerOptions()
                                .title(dataBean.getSkuId())
                                .period(dataBean.getRoomStatus())
                                .icon(BitmapDescriptorFactory.fromView(getView(dataBean.getPrice(), dataBean.getRoomStatus())))
                                .position(new LatLng(Double.valueOf(dataBean.getLat()) * 0.000001, Double.valueOf(dataBean.getLng()) * 0.000001))
                                .draggable(false);
                        marker = mAmap.addMarker(markerOption);
                        Animation animation = new ScaleAnimation(0,1,0,1);
                        animation.setInterpolator(new LinearInterpolator());
                        //整个移动所需要的时间
                        animation.setDuration(800);
                        //设置动画
                        marker.setAnimation(animation);
                        //开始动画
                        marker.startAnimation();
                        sumLats += dataBean.getLat();
                        sumLngs += dataBean.getLng();
                    }
                    total = result.size();
                    double anLat = (double) sumLats / total;
                    double anIng = (double) sumLngs / total;
                    moveCenter(new LatLng(anLat * 0.000001, anIng * 0.000001));
                } else {
                    UIUtils.showToastSafe("附近暂无房源");
                }
            }
        });
    }


    protected View getView(String price, int status) {
        View view = getLayoutInflater().inflate(R.layout.map_item_view, null);
        ImageView iv = view.findViewById(R.id.image);
        TextView textView = view.findViewById(R.id.textView);
        textView.setText(price);
        if (status == 1) {
            iv.setImageResource(R.mipmap.hotel_a);
        } else if (status == 5) {
            iv.setImageResource(R.mipmap.hotel_c);
        }
        return view;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (mAmap != null) {
            jumpPoint(marker);
          //  moveCenter(marker.getPosition());
            showRoomDetail(marker.getTitle());
        }
        switch (marker.getPeriod()) {
            case 1://可预定   绿色
                //showRoomDetail(marker.getTitle());
                break;
            case 5://维修房 红色
                UIUtils.showToastSafe("该房间已下架");
                break;
        }
        return true;
    }


    /**
     * marker点击时跳动一下
     */
    private void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mAmap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }


    /**
     * 查看房间详情
     *
     * @param skuId
     */
    private void showRoomDetail(String skuId) {
        final Dialog alertDialog = new Dialog(getActivity(), R.style.EasyListDialogStyle);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.pop_marker);
        window.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (dm.widthPixels);
        window.setAttributes(lp);
        Button btEdit = (Button) alertDialog.findViewById(R.id.bt_edit);
        final TextView tvRoomName = (TextView) alertDialog.findViewById(R.id.tv_roomName);
        final TextView tvRoomAddress = (TextView) alertDialog.findViewById(R.id.tv_roomAddress);
        final TextView tvPrice = (TextView) alertDialog.findViewById(R.id.textView4);
        final TextView tvRoomBond = (TextView) alertDialog.findViewById(R.id.textView5);
        final TextView tvStatus = (TextView) alertDialog.findViewById(R.id.tv_status);
        final TextView tvConfig = (TextView) alertDialog.findViewById(R.id.tv_config);
        final ImageView ivWifi = alertDialog.findViewById(R.id.iv_wifi);
        final ImageView ivBed = alertDialog.findViewById(R.id.iv_bed);
        final ImageView ivBathroom = alertDialog.findViewById(R.id.iv_bathroom);
        final ImageView ivWindow = alertDialog.findViewById(R.id.iv_window);
        final BannerLayout bannerLayout = alertDialog.findViewById(R.id.banner);
        HashMap<String, String> map = new HashMap<>();
        map.put("skuId", skuId);

        String autoSignStr = Constants.ROOM_DETAIL.substring(Constants.ROOM_DETAIL.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        String url = Constants.ROOM_DETAIL + "?token=" + id + "&sign=" + signStr;
        HttpClient.post(this, Constants.ROOM_DETAIL, map, new CallBack<RoomDetailsBean>() {
            @Override
            public void onSuccess(RoomDetailsBean result) {
                if (result != null) {
                    tvRoomName.setText(result.getSkuName());
                    tvRoomAddress.setText(result.getAddress() + "  " + result.getRoomNo());
                    tvPrice.setText(result.getPrice() + "");
                    tvRoomBond.setText(result.getRoomBond() + "");
                    if (result.getRoomStatus() == 5) {
                        Resources resources = getActivity().getBaseContext().getResources();
                        Drawable drawable = resources.getDrawable(R.drawable.bg_care);
                        tvStatus.setBackground(drawable);
                        tvStatus.setText("已下架");
                    }
                    String type = result.getRoomType();
                    if (("0").equals(type)) {
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  公寓型");
                    } else if (("1").equals(type)) {
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  酒店型");
                    } else if (("2").equals(type)) {
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  住宅型");
                    }

                    List<String> facilityIds = result.getFacilityIds();
                    List<String> imgUrls = result.getImgUrls();
                    if (facilityIds != null && facilityIds.size() > 0) {
                        for (String facilityId : facilityIds) {
                            if ("101".equals(facilityId)) {
                                ivWifi.setVisibility(View.VISIBLE);
                            } else if ("102".equals(facilityId)) {
                                ivBed.setVisibility(View.VISIBLE);
                            } else if ("103".equals(facilityId)) {
                                ivBathroom.setVisibility(View.VISIBLE);
                            } else if ("104".equals(facilityId)) {
                                ivWindow.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                    if (imgUrls != null && imgUrls.size() > 0) {
                        bannerLayout.setViewUrls(imgUrls);
                    } else {
                        imgUrls.add("http://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/1530259798549.jpg");
                        bannerLayout.setViewUrls(imgUrls);
                    }
                }
            }
        });

        btEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIUtils.startActivity(HomeStayListActivity.class);
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
                    && geocodeResult.getGeocodeAddressList().size() > 0) {
                GeocodeQuery a = geocodeResult.getGeocodeQuery();
                GeocodeAddress address = geocodeResult.getGeocodeAddressList().get(0);
                String addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
                        + address.getFormatAddress();
                //获取到的经纬度
                LatLonPoint latLongPoint = address.getLatLonPoint();
                double Lat = (float) latLongPoint.getLatitude();
                double Lon = (float) latLongPoint.getLongitude();
                mAmap.clear();
                moveCenter(new LatLng(Lat, Lon));
                addMarkersToMap(city);
            }
        }
    }
}
